const parse = require('url').parse
const methods = require('methods')
const Layer = require('./layer')
const Route = require('./route')

function Router() {
    this.stack = []
}
methods.forEach(method => {
    // 2.收集请求
    Router.prototype[method] = function (path, handlers) {
        const route = new Route()
        const layer = new Layer(path,route.dispatch.bind(route))
        layer.route = route
        this.stack.push(layer)
        route[method](path,handlers)
    }
})
Router.prototype.handle = function (req, res) {
    const { pathname } = parse(req.url)
    let index = 0
    const next = () => {
        if(index > this.stack.length){
            return res.end(`Can not get ${pathname}`)
        }
        const layer = this.stack[index++]
        const match = layer.match(pathname)
        if(match){
            req.params = req.params || {}
            Object.assign(req.params,layer.params)
        }
        // 4.外层只支持请求路径
        if(match){
            // 内层判断请求方法，此时 handler 指向 route 的 dispatch
            return layer.handler(req, res, next)
        }
        next()
    }
    next()
}

// 2.收集 use 中间件
Router.prototype.use = function(path,handlers){
    if(typeof path === 'function'){
        handlers.unshift(path)
        path = '/'
    }
    handlers.forEach(handler=>{
        const layer = new Layer(path,handler)
        layer.isUseMiddleware = true // 加个属性标记
        this.stack.push(layer)
    })
}

module.exports = Router